package com.jsjosem.aftersales.ui.worktickets;

import static com.jsjosem.aftersales.constant.Command.REFRESH_TICKET_LIST;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.icu.util.Calendar;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.widget.ViewPager2;

import com.borax12.materialdaterangepicker.date.DatePickerDialog;
import com.github.clans.fab.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.adapter.StateAdapter;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.api.WorkOrderApi;
import com.jsjosem.aftersales.data.response.BaseResponse;
import com.jsjosem.aftersales.databinding.FragmentWorkTicketsBinding;
import com.jsjosem.aftersales.enums.WorkOrderStatusEnum;
import com.jsjosem.aftersales.listener.ListenerManager;
import com.jsjosem.aftersales.request.AsyncRequest;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.collection.ListUtil;
import retrofit2.Call;
import retrofit2.Retrofit;

public class WorkTicketsFragment extends Fragment {

    private FragmentWorkTicketsBinding binding;

    private View view;

    private Spinner searchSp;

    private ImageButton btSearch;

    private Button btWeek, btMonth, btSelectDate;

    private TabLayout tabLayout;

    private ViewPager2 viewPager2;

    private Dialog loadingDialog;

    private List<String> stateList;

    private FloatingActionButton btMaintain, btInstallation, btTraining, btDebugger;

    private final Map<String, Integer> serviceTypeMap = new HashMap<String, Integer>() {{
        put("安装工单", 0);
        put("设备维修", 1);
        put("维保工单", 2);
        put("巡检工单", 3);
    }};

    private StateAdapter stateAdapter;


    Map<String, Integer> statusData;
    private ListenerManager listenerManager;
    private Context context;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentWorkTicketsBinding.inflate(inflater, container, false);
        view = binding.getRoot();
        context = view.getContext();
        listenerManager = ListenerManager.getInstance();
        initView();
        return view;
    }

    private void initView() {
        init();
        initTitle();
        initSpinner();
    }

    private void init() {
        btSearch = view.findViewById(R.id.bt_search);
        searchSp = view.findViewById(R.id.sp_select);
        btWeek = view.findViewById(R.id.bt_week);
        btMonth = view.findViewById(R.id.bt_month);
        btSelectDate = view.findViewById(R.id.bt_select_date);
        tabLayout = view.findViewById(R.id.tab_layout);
        viewPager2 = view.findViewById(R.id.ticket_view_page);
        btMaintain = view.findViewById(R.id.maintain);
//        btInstallation = view.findViewById(R.id.installation);
//        btTraining = view.findViewById(R.id.training);
//        btDebugger = view.findViewById(R.id.debugger);
        btWeek.setOnClickListener(v -> listenerManager.sendBroadCast(REFRESH_TICKET_LIST, "week", "OK"));
        btMonth.setOnClickListener(v -> listenerManager.sendBroadCast(REFRESH_TICKET_LIST, "month", "OK"));
        btMaintain.setOnClickListener(click -> {
            Intent intent = new Intent(getActivity(), MaintainActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("serviceType", serviceTypeMap.get("安装工单"));
            intent.putExtras(bundle);
            startActivity(intent);
        });
//        btInstallation.setOnClickListener(click -> {
//            Intent intent = new Intent(getActivity(), MaintainActivity.class);
//            Bundle bundle = new Bundle();
//            bundle.putInt("serviceType", serviceTypeMap.get("设备维修"));
//            intent.putExtras(bundle);
//            startActivity(intent);
//        });
//
//        btTraining.setOnClickListener(click -> {
//            Intent intent = new Intent(getActivity(), MaintainActivity.class);
//            Bundle bundle = new Bundle();
//            bundle.putInt("serviceType", serviceTypeMap.get("维保工单"));
//            intent.putExtras(bundle);
//            startActivity(intent);
//        });
//
//        btDebugger.setOnClickListener(click -> {
//            Intent intent = new Intent(getActivity(), MaintainActivity.class);
//            Bundle bundle = new Bundle();
//            bundle.putInt("serviceType", serviceTypeMap.get("巡检工单"));
//            intent.putExtras(bundle);
//            startActivity(intent);
//        });

        initDateSelector();
    }


    private void initDateSelector() {
        btSelectDate.setOnClickListener(click -> {
            Calendar now = Calendar.getInstance();
            DatePickerDialog dpd = DatePickerDialog.newInstance((view, year, monthOfYear, dayOfMonth, yearEnd, monthOfYearEnd, dayOfMonthEnd) -> {
                monthOfYear += 1;
                monthOfYearEnd += 1;
                if (year + monthOfYear + dayOfMonth > yearEnd + monthOfYearEnd + dayOfMonthEnd) {
                    Toast.makeText(getContext(), "开始日期不能大于结束日期", Toast.LENGTH_LONG).show();
                    return;
                }
                String format = "%d-%d-%d";
                String startDate = String.format(Locale.CHINA, format, year, monthOfYear, dayOfMonth);
                String endDate = String.format(Locale.CHINA, format, yearEnd, monthOfYearEnd, dayOfMonthEnd);
                String data = "date:" + startDate + "," + endDate;
                listenerManager.sendBroadCast(REFRESH_TICKET_LIST, data, "OK");
            }, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
            dpd.setStartTitle("请选择开始日期");
            dpd.setEndTitle("请选择结束日期");
            dpd.show(getActivity().getFragmentManager(), "Datepickerdialog");
        });
    }

    private void initTitle() {

        Retrofit mRetrofit = RetrofitClient.getInstance();
        WorkOrderApi workOrderApi = mRetrofit.create(WorkOrderApi.class);
        Call<BaseResponse<Map<String, Integer>>> getStatusCounts = workOrderApi.getStatusCounts();
        AsyncRequest<BaseResponse<Map<String, Integer>>> request = new AsyncRequest<>();

        stateList = new ArrayList<>();
        stateList.add("未完成");
        stateList.addAll(Arrays.stream(WorkOrderStatusEnum.values()).map(WorkOrderStatusEnum::getDesc).collect(Collectors.toList()));
        List<Fragment> fragments = new ArrayList<>();
        stateList.forEach(state -> fragments.add(TicketListItemFragment.newInstance(state)));
        stateAdapter = new StateAdapter((FragmentActivity) getContext(), fragments);
        viewPager2.setAdapter(stateAdapter);
        loadingShow();
        request.sendRequest(getStatusCounts, res -> {
            statusData = res.getData();
            new TabLayoutMediator(tabLayout, viewPager2, (tab, position) -> {
                String state = stateList.get(position);
                Integer count = statusData.get(state);
                tab.setText(state + " " + count);
            }).attach();
            loadingDialog.dismiss();
        }, err -> {
            loadingDialog.dismiss();
            Toast.makeText(getContext(), err.toString(), Toast.LENGTH_SHORT).show();
        });

        tabLayout.setTabTextColors(Color.parseColor("#666666"), Color.parseColor("#101010"));
        tabLayout.setBackground(new ColorDrawable(Color.parseColor("#ffffff")));

        btSearch.setOnClickListener(searchClick -> {
            Intent intent = new Intent(getContext(), WorkTicketsSearchViewActivity.class);
            startActivity(intent);
        });
    }

    private void initSpinner() {
        List<String> selectList = ListUtil.of("我的部门", "我协助的", "我负责的", "我创建的");
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getContext(), R.layout.work_order_item_select, selectList);
        searchSp.setAdapter(arrayAdapter);
        searchSp.setSelection(0, true);
        // 点击下拉框，请求数据
        searchSp.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String aboutMe = null;
                switch (position) {
                    case 0:
                        aboutMe = "department";
                        break;
                    case 1:
                        aboutMe = "assist";
                        break;
                    case 2:
                        aboutMe = "master";
                        break;
                    case 3:
                        aboutMe = "create";
                        break;
                }
                listenerManager.sendBroadCast(REFRESH_TICKET_LIST, aboutMe, "OK");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    public void loadingShow() {
        loadingDialog = new Dialog(context, R.style.normal_dialog_style);
        View loadingView = View.inflate(context, R.layout.dialog_loading, null);
        loadingDialog.setContentView(loadingView);
        //使得点击对话框外部不消失对话框
        loadingDialog.setCanceledOnTouchOutside(false);
        AVLoadingIndicatorView avi = loadingView.findViewById(R.id.avi);
        avi.show();
        loadingDialog.show();
    }

}